package cn.cloud.all.security.web.util.matcher;

import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;

/**
 * A {@link RequestMatcher} that can be used to match request that contain a header with
 * an expected header name and an expected value.
 *
 * <p>
 * For example, the following will match an request that contains a header with the name
 * X-Requested-With no matter what the value is.
 * </p>
 *
 * <pre>
 * RequestMatcher matcher = new RequestHeaderRequestMatcher(&quot;X-Requested-With&quot;);
 * </pre>
 * <p>
 * Alternatively, the RequestHeaderRequestMatcher can be more precise and require a
 * specific value. For example the following will match on requests with the header name
 * of X-Requested-With with the value of "XMLHttpRequest", but will not match on header
 * name of "X-Requested-With" with the value of "Other".
 *
 * <pre>
 * RequestMatcher matcher = new RequestHeaderRequestMatcher(&quot;X-Requested-With&quot;,
 * 		&quot;XMLHttpRequest&quot;);
 * </pre>
 * <p>
 * The value used to compare is the first header value, so in the previous example if the
 * header "X-Requested-With" contains the values "Other" and "XMLHttpRequest", then it
 * will not match.
 */
public final class RequestHeaderRequestMatcher implements RequestMatcher {
    private final String expectedHeaderName;
    private final String expectedHeaderValue;

    public RequestHeaderRequestMatcher(String expectedHeaderName) {
        this(expectedHeaderName, null);
    }

    public RequestHeaderRequestMatcher(String expectedHeaderName, String expectedHeaderValue) {
        Assert.notNull(expectedHeaderName, "headerName cannot be null");
        this.expectedHeaderName = expectedHeaderName;
        this.expectedHeaderValue = expectedHeaderValue;
    }

    public boolean matches(HttpServletRequest request) {
        String actualHeaderValue = request.getHeader(expectedHeaderName);
        if (expectedHeaderValue == null) {
            return actualHeaderValue != null;
        }

        return expectedHeaderValue.equals(actualHeaderValue);
    }

    @Override
    public String toString() {
        return "RequestHeaderRequestMatcher [expectedHeaderName=" + expectedHeaderName + ", expectedHeaderValue=" + expectedHeaderValue + "]";
    }
}
